import { reqShopList, reqDeleteCartList, reqUpdateCheckedById } from "@/api"
const state = {
    shopList: []
}
const mutations = {
    GETSHOPLIST(state, shopList) {
        state.shopList = shopList
    }
}
const actions = {
    async getShopList({ commit }) {
        let result = await reqShopList()
        if (result.code == 200) {
            commit('GETSHOPLIST', result.data)
        }
    },
    //删除购物车数据
    async deleteCartList({ commit }, id) {
        let result = await reqDeleteCartList(id)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //修改商品的选中状态
    async updateCheckedById({ commit }, { id, isChecked }) {
        let result = await reqUpdateCheckedById(id, isChecked)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //删除选中的全部产品        
    deleteAllCheckCart({ dispatch, getters }) {
        
        let Allpromise = []
        getters.shopList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCartList',item.skuId) : ''
            //将每一次返回的promise加入到数组
            Allpromise.push(promise)
        })
        //只有全部的p1 p2...成功 才返回成功 一个失败返回失败
        return Promise.all(Allpromise)
    },
    //修改所有商品选中状态
    updateAllChecked({dispatch,state},isChecked){
        let Allpromise =[]
        state.shopList[0].cartInfoList.forEach(item=>{
            let promise=dispatch("updateCheckedById",{id:item.skuId,isChecked})
            Allpromise.push(promise)
        })
        //最终返回结果
        return Promise.all(Allpromise)
    }
}
const getters = {
    shopList(state) {
        return state.shopList[0] || {}
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}